package com.my.oschina.ui;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.my.oschina.R;
import com.my.oschina.adapter.ListViewCommentAdapter;
import com.my.oschina.app.AppContext;
import com.my.oschina.app.AppException;
import com.my.oschina.bean.BlogCommentList;
import com.my.oschina.bean.Comment;
import com.my.oschina.bean.CommentList;

/**
 * 评论列表-分为来自资讯的新闻和博客，两者的请求方式不同
 * 
 * @author XuShaoJie
 * @version 2013-07-11
 */
public class CommentActivity extends OscBaseActivity {

	private PullToRefreshListView mPullRefreshListView;
	private ListViewCommentAdapter mNewsAdapter;
	private List<Comment> lvNewsDataList = new ArrayList<Comment>();
	private int lvSumData;// 加载的总数目

	private AppContext appContext;// 全局Context

	private int curId;
	private int curCatalog;
	private static String COMM_FLAG;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ptr_list);

		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(true);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		setTitle(R.string.comment);

		curId = getIntent().getIntExtra("curId", 0);
		curCatalog = getIntent().getIntExtra("curCatalog", 0);
		COMM_FLAG = getIntent().getStringExtra("blogType");
		appContext = (AppContext) getApplication();

		mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
		mPullRefreshListView.setMode(Mode.BOTH);
		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {

						String label = "上次刷新时间:"
								+ DateUtils.formatDateTime(appContext,
										System.currentTimeMillis(),
										DateUtils.FORMAT_SHOW_TIME
												| DateUtils.FORMAT_SHOW_DATE
												| DateUtils.FORMAT_ABBREV_ALL);

						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);

						if (mPullRefreshListView.getCurrentMode() == Mode.PULL_FROM_START) {
							lvNewsDataList.clear();
							lvSumData = 0;
							mNewsAdapter.notifyDataSetChanged();
						}

						// 加载数据异步处理任务
						if (COMM_FLAG != null
								&& COMM_FLAG.equals("BlogCommentList")) {
							new GetBlogCommentsTask().execute();
						} else {
							new GetCommentsTask().execute();
						}
					}
				});

		mNewsAdapter = new ListViewCommentAdapter(this, lvNewsDataList,
				R.layout.comment_listitem);
		mPullRefreshListView.setAdapter(mNewsAdapter);

		// // TODO 第一次启动时候加载数据
		if (COMM_FLAG != null && COMM_FLAG.equals("BlogCommentList")) {
			new GetBlogCommentsTask().execute();
		} else {
			new GetCommentsTask().execute();
		}

	}

	/**
	 * 加载数据AsyncTask
	 */
	private class GetCommentsTask extends AsyncTask<String, Void, CommentList> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			setSupportProgressBarIndeterminateVisibility(true);
		}

		@Override
		protected CommentList doInBackground(String... params) {

			// 当前pageIndex
			int pageIndex = lvSumData / 20;
			if (curId != 0) {
				try {
					return appContext.getCommentList(curCatalog, curId,
							pageIndex, true);
				} catch (AppException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(CommentList result) {
			super.onPostExecute(result);
			setSupportProgressBarIndeterminateVisibility(false);

			List<Comment> friendList = result.getCommentlist();
			// 加载成功且如果有数据
			if (result != null && friendList.size() > 0) {

				lvSumData += friendList.size();
				lvNewsDataList.addAll(result.getCommentlist());
				mNewsAdapter.notifyDataSetChanged();
				// Call onRefreshComplete when the list has been refreshed.
				mPullRefreshListView.onRefreshComplete();

				if (friendList.size() < 20) {
					mPullRefreshListView.setMode(Mode.PULL_FROM_START);
					// 添加监听器
					mPullRefreshListView
							.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
								@Override
								public void onLastItemVisible() {
									Toast.makeText(CommentActivity.this,
											"已加载全部", Toast.LENGTH_SHORT).show();
								}
							});

				} else if (friendList.size() == 20) {
					mPullRefreshListView.setMode(Mode.BOTH);
					// 取消监听
					mPullRefreshListView.setOnLastItemVisibleListener(null);
				}
			}
			// 加载失败或者没有数据
			else {
				Toast.makeText(CommentActivity.this, "加载失败，请重试",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	/**
	 * 加载数据AsyncTask
	 */
	private class GetBlogCommentsTask extends
			AsyncTask<String, Void, BlogCommentList> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			setSupportProgressBarIndeterminateVisibility(true);
		}

		@Override
		protected BlogCommentList doInBackground(String... params) {

			// 当前pageIndex
			int pageIndex = lvSumData / 20;
			try {
				return appContext.getBlogCommentList(curId, pageIndex, true);
			} catch (AppException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(BlogCommentList result) {
			super.onPostExecute(result);
			setSupportProgressBarIndeterminateVisibility(false);

			List<Comment> friendList = result.getCommentlist();
			// 加载成功且如果有数据
			if (result != null && friendList.size() > 0) {

				lvSumData += friendList.size();
				lvNewsDataList.addAll(result.getCommentlist());
				mNewsAdapter.notifyDataSetChanged();
				// Call onRefreshComplete when the list has been refreshed.
				mPullRefreshListView.onRefreshComplete();

				if (friendList.size() < 20) {
					mPullRefreshListView.setMode(Mode.PULL_FROM_START);
					// 添加监听器
					mPullRefreshListView
							.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
								@Override
								public void onLastItemVisible() {
									Toast.makeText(CommentActivity.this,
											"已加载全部", Toast.LENGTH_SHORT).show();
								}
							});

				} else if (friendList.size() == 20) {
					mPullRefreshListView.setMode(Mode.BOTH);
					// 取消监听
					mPullRefreshListView.setOnLastItemVisibleListener(null);
				}
			}
			// 加载失败或者没有数据
			else {
				Toast.makeText(CommentActivity.this, "加载失败，请重试",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_refresh, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case R.id.menu_refresh:
			lvNewsDataList.clear();
			lvSumData = 0;
			mNewsAdapter.notifyDataSetChanged();
			if (COMM_FLAG != null && COMM_FLAG.equals("BlogCommentList")) {
				new GetBlogCommentsTask().execute();
			} else {
				new GetCommentsTask().execute();
			}
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

}
